package com.yitiao.multithread.cas;

import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * 解决 ABA 问题
 */
public class CASStampExample {
    private static AtomicStampedReference<Integer> atomicStampedRef = new AtomicStampedReference<>(100, 0);
    public static void main(String[] args) throws InterruptedException {
        int[] stampHolder = new int[1]; // 用于存储版本号

        // 解决 ABA 问题
        new Thread(() -> {
            int stamp = atomicStampedRef.getStamp(); // 获取当前版本号
            atomicStampedRef.compareAndSet(100, 101, stamp, stamp + 1); // A -> B
            atomicStampedRef.compareAndSet(101, 100, stamp + 1, stamp + 2); // B -> A
        }).start();

        Thread.sleep(1000);

        // 检查最终结果
        System.out.println("Current value: " + atomicStampedRef.get(stampHolder) + ", Stamp: " + atomicStampedRef.getStamp());
    }
}
